#include <iostream>

#include <gtest/gtest.h>

#include "melon/client/thrift_client_pool.h"
#include "UserProfileService.h"

using imserver::UserProfile;
using imserver::UserProfileMap;
using imserver::UserProfileServiceClient;
using imserver::SessionList;
using melon::client::ClientPool;

void * ThreadFun(void * data) {
  ClientPool<UserProfileServiceClient> * pool = (ClientPool<UserProfileServiceClient>*)data;
  
  // const char * addrs[] = {"127.0.0.1:9091", "127.0.0.1:9093"};
  const char * addrs[] = {"10.16.15.197:9196"};
  int addr_count = sizeof(addrs) / sizeof(char*);

  UserProfileServiceClient * p = NULL;
  UserProfile up;
  UserProfileMap ups;

  for (int i = 0; i < 100; ++i) {
  // for (int i = 0; i < 1; ++i) {
    std::string addr(addrs[i % addr_count]);
    p = pool->Alloc(addr);
    if (!p) {
      continue;
    }

    bool success = true;
    try {
      p->Get(up, 127646892 + i);
      std::cout << up.qid << " username=" << up.username << std::endl;
      std::vector<int64_t> qids;
      qids.push_back(127646892 + i);
      qids.push_back(123924630 + i);
      qids.push_back(144240991 + i);
      qids.push_back(144240991 + i);
      p->BatchGet(ups, qids);
      std::cout << "BatchGet.size()=" << ups.size() << std::endl;

      for(UserProfileMap::const_iterator it = ups.begin(); it != ups.end(); ++it) {
        std::cout << it->first << " " << it->second.qid << " username=" << it->second.username << std::endl;
      }
    } catch (const std::exception & e) {
      std::cout << addr << " error:" << e.what() << std::endl;
      success = false;
    }
    pool->Release(addr, p, success);
    usleep(1000);
  }
  return NULL;
}

const int kThreadCount = 1;

int main() {
  ClientPool<UserProfileServiceClient> pool(800);

  pthread_t ts[kThreadCount];

  for (int i = 0; i < kThreadCount; ++i) {
    pthread_create(&ts[i], NULL, ThreadFun, &pool);
  }

  for (int i = 0; i < kThreadCount; ++i) {
    pthread_join(ts[i], NULL);
  }
  return 0;
}

